package com.hwadee.property.controller.info;

import com.hwadee.property.pojo.Complain;
import com.hwadee.property.service.IComplainService;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.FileUtil;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/complain")
@Api(tags = "投诉建议-ComplainController")
@CrossOrigin
public class ComplainController {

    @Autowired
    private IComplainService complainService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private FileUtil fileUtil;

    @GetMapping("/personal")
    @ApiOperation(value = "【业主】查询本人投诉或建议", notes = "返回当前账号个人的所有投诉或建议列表")
    public AjaxResult getAllComplains(@RequestHeader("Authorization") String token) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询投诉或建议记录
            List<Complain> complains = complainService.listByOwnerId(userId);

            // 返回投诉或建议记录
            return AjaxResult.success(complains);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询本人投诉或建议失败");
        }
    }

    @GetMapping("/property")
    @ApiOperation(value = "【物业】查询所在小区的投诉或建议", notes = "返回当前物业账号所在小区的所有投诉或建议列表")
    public AjaxResult getAllComplainsForProperty(@RequestHeader("Authorization") String token) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据小区ID查询投诉或建议记录
            List<Complain> complains = complainService.listByCommunityId(userService.getById(userId).getCommunityId());

            // 返回投诉或建议记录
            return AjaxResult.success(complains);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询所在小区的投诉或建议失败");
        }
    }

    @PutMapping("/property/update")
    @ApiOperation(value = "【物业】处理投诉或建议", notes = "物业根据投诉或建议 ID 对投诉或建议记录进行处理反馈。状态有：待处理、处理中、已完成、已取消")
    public AjaxResult updateComplainStatus(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "投诉或建议 ID", required = true) @RequestParam Long complainId,
            @ApiParam(value = "新状态", required = false) @RequestParam String status,
            @ApiParam(value = "处理反馈", required = false) @RequestParam String measure) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            Complain complain = new Complain();
            complain.setId(complainId);
            complain.setMeasure(measure);
            complain.setProcessingStatus(status);
            complain.setHandlerId(userId);
            if (status.equals("已完成")) complain.setCompletionDate(DateUtil.dateToString(new Date()));
            boolean success = complainService.updateById(complain);
            return success ? AjaxResult.success() : AjaxResult.fail("处理投诉或建议失败");
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("token解析异常或其他异常，处理投诉或建议失败");
        }
    }

    @PostMapping("/{communityId}")
    @ApiOperation(value = "【业主】新增投诉或建议", notes = "添加一条投诉或建议记录。默认processing_status为“待处理”，默认complain_date为“当前时间”。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "complaintContent", value = "投诉/建议内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "attachment", value = "附件", required = false, dataType = "MultipartFile", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String", paramType = "query")
    })
    public AjaxResult addComplain(@RequestHeader("Authorization") String token,
            @PathVariable Long communityId,
            @RequestParam String complaintContent,
            @RequestParam(required = false) MultipartFile attachment,
            @RequestParam String type) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }
        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);
            // 进行投诉建议提交
            Complain complain = new Complain();
            complain.setCommunityId(communityId);
            complain.setOwnerId(userId);
            complain.setType(type);
            complain.setComplainContent(complaintContent);
            if (attachment != null) {
                String attachmentPath = fileUtil.uploadFileAndGetPath(attachment, "complain");
                complain.setAttachment(attachmentPath);
            }
            boolean result = complainService.addComplain(complain);
            return result ? AjaxResult.success() : AjaxResult.fail("complainService.addComplain失败，新增投诉或建议失败");
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("token解析异常或其他异常，新增投诉或建议失败");
        }
    }

    @PutMapping("/{id}/status")
    @ApiOperation(value = "【管理员】更新投诉或建议的处理状态", notes = "根据ID更新投诉或建议的处理状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "投诉或建议的ID", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "status", value = "新的处理状态", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "handlerId", value = "处理人员ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "completionDate", value = "处理完成时间", dataType = "String", paramType = "query")
    })
    public AjaxResult updateStatus(@RequestHeader("Authorization") String token,
            @PathVariable Long id,
            @RequestParam String status,
            @RequestParam(required = false) Long handlerId,
            @RequestParam(required = false) String completionDate) throws ParseException {
        boolean result = complainService.updateStatus(id, status, handlerId, completionDate);
        return result ? AjaxResult.success() : AjaxResult.fail("更新处理状态失败");
    }

    @GetMapping
    @ApiOperation(value = "【管理员】分页查询投诉或建议列表", notes = "分页查询投诉或建议列表，支持按小区ID、业主ID和处理状态过滤")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, dataType = "int", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "communityId", value = "小区ID（可选）", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "ownerId", value = "业主ID（可选）", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "处理状态（可选）", dataType = "String", paramType = "query")
    })
    public AjaxResult getComplainListPage(@RequestHeader("Authorization") String token,
            @RequestParam int current,
            @RequestParam int size,
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String status) {
        PageResult<Complain> pageResult = complainService.getComplainListPage(current, size, communityId, ownerId, status);
        return AjaxResult.success(pageResult);
    }

    @GetMapping("/count/unprocessed")
    @ApiOperation(value = "【管理员】统计未处理的投诉或建议数量", notes = "根据小区ID统计未处理的投诉或建议数量")
    @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "Long", paramType = "query")
    public AjaxResult getUnprocessedComplainCount(@RequestHeader("Authorization") String token,
            @RequestParam Long communityId) {
        long count = complainService.getUnprocessedComplainCount(communityId);
        return AjaxResult.success(count);
    }
}
